#!/usr/bin/env python3
# encoding: utf-8
import re
import os
import sys
import oss2
import time
import datetime
import hashlib
import requests

from .config import oss_config
from .config import xiguadaili_config


def get_proxy():
    proxy_url = 'http://api3.xiguadaili.com/ip/'
    res = requests.get(proxy_url, data=xiguadaili_config)
    print(res.text)
    return res.text

def md5(val):
    if type(val)!=bytes:
        val = val.encode('utf-8')
    return hashlib.md5(val).hexdigest()

def timestamp():
    return time.mktime(datetime.datetime.now().timetuple())

def to_timestamp(dt_str, tz_str='UTC+8:00'):
    # str-->datetime
    dt = datetime.datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')
    #UTC中获取时区信息
    tz_r = re.match(r'^UTC([+|-]\d{1,2}):00$', tz_str)
    # 创建时区UTC
    tz = datetime.timezone(datetime.timedelta(hours=int(tz_r.group(1))))
    # 利用tzinfo属性将datetime强制设置成指定时区
    # 返回timestamp
    dt = dt.replace(tzinfo=tz)
    return dt.timestamp()

def download_img(url, root_path='/tmp/img/', headers=None):
    try:
        if not url:
            return ''
        img_ext = 'png'
        filename = ''
        binary_data = b''
        if url[0:22]=='data:image/png;base64,':
            from binascii import a2b_base64
            data = bytes(url[22:], encoding='utf8')
            binary_data = a2b_base64(data)
            filename = md5(binary_data)
            img_ext = 'png'
        else:
            if url[0:2]=='//':
                url = 'https:'+url
            url = url.replace('\\','')
            r = requests.get(url, headers=headers, timeout=30000)
            binary_data = r.content
            filename = md5(url.split('/')[-1])
            img_ext = r.headers['Content-Type'].split('/')[1]
        # end if
        path = root_path + filename
        if not os.path.exists(root_path):
            os.makedirs(root_path)
        img_file = '%s.%s' % (path, img_ext, )
        if not os.path.exists(img_file):
            with open(img_file,'wb') as f:
                f.write(binary_data)
        return (img_file, img_ext)
    except TimeoutError as e:
        print(url)
    except Exception as e:
        print(url)
        raise e

def oss(subpath, url, headers=None):
    if not url:
        return ''
    (img_path, ext) = download_img(url, headers=headers)
    imgfile = '%s/%s.%s' % (subpath, md5(url), ext)

    accesskeyid = oss_config.get('accesskeyid')
    accesskey = oss_config.get('accesskey')
    endpoint = oss_config.get('endpoint')
    bucket_name = oss_config.get('bucket_name')
    ossid = oss_config.get('')
    auth = oss2.Auth(accesskeyid, accesskey)
    bucket = oss2.Bucket(auth, 'http://' % (endpoint,), bucket_name)
    bucket.put_object_from_file(imgfile, img_path)
    return 'http://%s.%s/%s' % (bucket_name,endpoint, imgfile)

if __name__ == '__main__':
    t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00')
    t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')
    print(t1)
    print(t2)